<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="phone">
      <el-input v-model="loginForm.phone" placeholder="请输入手机号码">
        <template #prefix>
          <el-icon class="el-input__icon"><user /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <ValidPhone :phone="loginForm.phone" v-model:code="loginForm.code" session-name="login_session"></ValidPhone>
    </el-form-item>
  </el-form>
  <slot></slot>
  <div class="login-btn">
    <el-button :icon="CircleClose" round @click="resetForm(loginFormRef)" size="large">重置</el-button>
    <el-button :icon="UserFilled" round @click="login(loginFormRef)" size="large" type="primary" :loading="loading">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { FormRules } from "element-plus";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { checkPhoneNumber } from "@/utils/eleValidate";
import ValidPhone from "@/components/validPhone/index.vue";

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules: FormRules = reactive({
  phone: [{ validator: checkPhoneNumber, trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive({
  phone: "",
  code: ""
});

// login
const emits = defineEmits(["valid"]);
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    emits("valid", { ...loginForm, loginType: 1 });
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
